package main

import (
	"bufio"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
	"time"
)

//var loger *log.Logger

const (
	InitDate = "2006-01-02"
	DateTime = "2006-01-02 15:04:05"
)

func init() {
	createLogFile()
}

func main() {
	WalkDir("/Users/huanglu/Desktop/ogg/")
}

func createLogFile() {
	now := time.Now()
	nowDate := now.Format(InitDate)
	file := "./log/" + nowDate + ".txt"
	bool, _ := PathExists("./log/")
	if !bool {
		os.Mkdir("./log/", os.ModePerm)
	} else {
		bool1, _ := PathExists(file)
		if bool1 {
			return
		}
	}
	logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
	if err != nil {
		panic(err)
	}
	log.SetOutput(logFile) // 将文件设置为log输出的文件
	log.SetPrefix("[ogg2mp3]")
	log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
	return
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func WalkDir(dir string) {
	filepath.Walk(dir, func(fileName string, fi os.FileInfo, err error) error {
		if !fi.IsDir() {
			n1 := fileName
			n2 := strings.Replace(fileName, " ", "", -1)
			log.Println(n2)
			err = os.Rename(n1, n2)
			if err != nil {
				log.Println(err)
			}

			ext := path.Ext(fileName)

			mp3dir := path.Dir(dir + "mp3/")
			log.Println(mp3dir)
			//判断mp3存放目录是否存在
			bool, _ := PathExists(mp3dir)
			if !bool {
				os.MkdirAll(mp3dir, os.ModePerm)
				if err != nil && !os.IsExist(err) {
					log.Fatal(err)
				}
			}
			if ext == ".ogg" {
				//判断是否已经转过了
				mp3name := strings.TrimSuffix(fileName, ext) + ".mp3"
				mp3name = strings.Replace(mp3name, " ", "", -1)
				fExist, _ := PathExists(mp3name)
				if !fExist {

					c := `ffmpeg -i ` + n2 + ` -acodec libmp3lame ` + mp3name
					log.Println(c)
					ExecCommand(c)

				}
			}
		}
		return nil
	})
}

// ExecCommand 运行命令并实时查看运行结果
func ExecCommand(command string) error {
	cmd := exec.Command("bash", "-c", command)

	stdout, _ := cmd.StdoutPipe()
	stderr, _ := cmd.StderrPipe()

	if err := cmd.Start(); err != nil {
		log.Println("Error:The command is err: ", err.Error())
		return err
	}
	ch := make(chan string, 100)
	stdoutScan := bufio.NewScanner(stdout)
	stderrScan := bufio.NewScanner(stderr)
	go func() {
		for stdoutScan.Scan() {
			line := stdoutScan.Text()
			ch <- line
		}
	}()
	go func() {
		for stderrScan.Scan() {
			line := stderrScan.Text()
			ch <- line
		}
	}()
	var err error
	go func() {
		err = cmd.Wait()
		if err != nil && !strings.Contains(err.Error(), "exit status") {
			log.Println("wait:", err.Error())
		}
		close(ch)
	}()
	for line := range ch {
		log.Println(line)
	}
	return err
}

// ExecCommandWithResult 运行命令并获取结果
func ExecCommandWithResult(command string) string {
	out, err := exec.Command("bash", "-c", command).CombinedOutput()
	if err != nil && !strings.Contains(err.Error(), "exit status") {
		log.Println("err: " + err.Error())
		return ""
	}
	return string(out)
}
